<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="10">
          <a-col :md="4" :sm="24">
            <a-form-item label="查询类别">
              <a-select allowClear v-model="queryParam.Condition">
                <a-select-option key="cCusName">客户名称</a-select-option>
                <a-select-option key="cCusCode">客户编码</a-select-option>
                <a-select-option key="CODE">出库单号</a-select-option>
                <!-- <a-select-option key ="cRdCode">收发类别编码</a-select-option>
                <a-select-option key="cPersonCode">业务员编码</a-select-option>
                <a-select-option key="cPTCode">采购类型编码</a-select-option>
                <a-select-option key="cSTCode">销售类型编码</a-select-option> -->
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item>
              <a-input v-model="queryParam.Keyword" placeholder="关键字" @keydown.enter="getDataList" />
            </a-form-item>
          </a-col>
          <a-col :md="14" :sm="24">
            <a-select
              style="width: 100px; margin-left: 8px"
              v-model="selectTime"
              @change="changeTime"
              name="radioGroup"
              :default-value="0"
            >
              <a-select-option :value="index" v-for="(i, index) in ['一个月', '三个月', '六个月', '自定义']" :key="i">
                {{ i }}
              </a-select-option>
            </a-select>
            <a-range-picker style="margin-left: 8px; width: 220px" :disabled="timeDisabled" v-model="time" />
            <a-button
              style="margin-left: 10px"
              type="primary"
              @click="
                () => {
                  this.pagination.current = 1
                  this.getDataList()
                }
              "
              >查询</a-button
            >
            <a-button style="margin: 0 8px" @click="repossess">重置</a-button>
            <a-button type="primary" icon="download" @click="downloadTemplate">导出</a-button>
            <a-select
              allowClear
              ref="select"
              v-model:value="queryParam.selectType"
              placeholder="发票状态"
              style="width: 120px; margin-left: 8px"
              @change="getDataList()"
            >
              <a-select-option :value="-1">未开票</a-select-option>
              <a-select-option :value="10">已开票</a-select-option>
              <a-select-option :value="20">已被红冲</a-select-option>
              <a-select-option :value="30">已被作废</a-select-option>
              <a-select-option :value="40">失控</a-select-option>
              <a-select-option :value="50">异常</a-select-option>
              <a-select-option :value="60">待红冲</a-select-option>
              <a-select-option :value="70">待作废</a-select-option>
              <a-select-option :value="0">未返回状态</a-select-option>
            </a-select>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-table
      ref="table"
      :scroll="{ y: 'calc(100vh - 330px)', x: 2040 }"
      :columns="columns"
      :dataSource="data"
      :pagination="pagination"
      :loading="loading"
      @change="handleTableChange"
      :bordered="true"
      size="small"
    >
      <span slot="CreateTime" slot-scope="CreateTime">{{ timeFormat(CreateTime) }}</span>
      <span slot="state" slot-scope="text, record">
        <template>
          <!-- <a-tag v-if="record.type == 1" color="blue">
            已开票
          </a-tag>
          <a-tag v-else-if="record.type == 0" color="orange">
            未开票
          </a-tag> -->
          <a-tag v-if="record.type == 10" color="blue"> 已开票 </a-tag>
          <a-tag v-else-if="record.type == 20" color="red"> 已被红冲 </a-tag>
          <a-tag v-else-if="record.type == 30" color="red"> 已被作废 </a-tag>
          <a-tag v-else-if="record.type == 40" color="orange"> 失控 </a-tag>
          <a-tag v-else-if="record.type == 50" color="orange"> 异常 </a-tag>
          <a-tag v-else-if="record.type == 60" color="orange"> 待红冲 </a-tag>
          <a-tag v-else-if="record.type == 70" color="orange"> 待作废 </a-tag>
          <a-tag v-else-if="record.type == 0" color="orange"> 未返回状态 </a-tag>
          <a-tag v-else color="orange"> 未开票 </a-tag>
        </template>
      </span>
      <span slot="Invoicenumber" slot-scope="text, record">
        <template>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>{{ ShowNumber(record) }}</span>
            </template>
            {{ ShowNumber(record, true) }}
          </a-tooltip>
        </template>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleView(record.Id, record)">查看</a>
          <a-divider v-if="record.type != 1" type="vertical" />
          <a v-if="record.type != 1" @click="handleEdit(record)">编辑</a>
        </template>
      </span>
    </a-table>
    <a-drawer
      title="修改信息"
      placement="right"
      width="40%"
      :closable="false"
      :visible="visible"
      @close="
        () => {
          ;(visible = false), (editEntitya = {})
        }
      "
    >
      <a-form-model
        ref="editEntity"
        :model="editEntitya"
        :rules="rules"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 12 }"
      >
        <a-button @click="pushAddList" type="primary">添加</a-button>
        <a-form-model-item label="发票号码:" prop="submitNumber">
          <a-input v-model="editEntitya.submitNumber" />
        </a-form-model-item>
        <a-form-model-item label="发票代码:" prop="Invoicecode">
          <a-input v-model="editEntitya.submitCode" />
        </a-form-model-item>

        <div>
          <div
            v-for="(i, index) in NumberList"
            style="margin: 10px 0 10px 0px; color: #333; font-size: 20px"
            :key="index"
          >
            <span style="color: #666">发票号码/发票代码</span
            ><span style="font-weight: 600; margin-left: 10px">{{ NumberList[index] }}</span
            >/<span style="font-weight: 600">{{ CodeList[index] }}</span>
            <a-button style="margin-left: 5px" type="primary" @click="del(index)">删除</a-button>
          </div>
        </div>
      </a-form-model>
      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '4px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1,
        }"
      >
        <a-button
          @click="
            () => {
              ;(visible = false), (editEntity = {})
            }
          "
          >取消</a-button
        >&nbsp; <a-button type="primary" @click="handleSubmit">确定</a-button>&nbsp;
      </div>
    </a-drawer>
    <edit-form ref="editForm" :parentObj="this"></edit-form>
  </a-card>
</template>

<script>
import EditForm from './EditForm'
import moment from 'moment'
import { invoiceNumberAbbr } from '@/utils/Tools.js'

const columns = [
  { title: '发货单号', dataIndex: 'CODE', align: 'center', width: '150px' },
  // { title: '出库单号', dataIndex: 'CODE', align: 'center', width: '150px' },
  {
    title: '发票号码',
    dataIndex: 'Invoicenumber',
    align: 'center',
    width: '150px',
    scopedSlots: { customRender: 'Invoicenumber' },
  },
  { title: '发票代码', dataIndex: 'Invoicecode', align: 'center', width: '150px' },
  { title: '客户编码', dataIndex: 'cCusCode', width: '180px' },
  { title: '客户名称', dataIndex: 'cCusName', width: '300px' },
  {
    title: '单据日期',
    dataIndex: 'madedate',
    align: 'center',
    width: '120px',
    customRender: (value) => {
      if (value) {
        return value.substring(0, 10)
      }
    },
  },
  {
    title: '申请发票日期',
    dataIndex: 'CreateTime',
    align: 'center',
    width: '120px',
    customRender: (value) => {
      if (value) {
        return value.substring(0, 10)
      }
    },
  },
  { title: '单据类型', dataIndex: 'vouchertypeName', align: 'center', width: '150px' },
  { title: '业务类型', dataIndex: 'BusName', align: 'center', width: '80px' },
  { title: '制单人', dataIndex: 'maker', align: 'center', width: '80px' },
  { title: '数量', dataIndex: 'InvoicingQuantity', align: 'right', width: '150px' },
  { title: '金额', dataIndex: 'InvoicingAmount', align: 'right', width: '150px' },
  { title: '销售类型', dataIndex: 'StyleNmame', align: 'center', width: '80px' },
  { title: '开票状态', dataIndex: 'state', scopedSlots: { customRender: 'state' }, align: 'center', width: '80px' },
  // { title: '收货地址', dataIndex: 'cShipAddress', width: '20%', ellipsis: true },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' },
    width: '100px',
  },
]

export default {
  components: {
    EditForm,
  },
  mounted() {
    this.$nextTick(() => {
      // 页面渲染完成后的回调
      // this.tableHeight = this.getTableHeight(true) + 24
      this.time = [
        this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1)),
        this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0)),
      ]
      this.getDataList()
    })
  },
  data() {
    return {
      data: [],
      submitNumber: '',
      submitCode: '',
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面可以通过下拉框进行选择
        showSizeChanger: true,
      },
      filters: {},
      visible: false,
      selectTime: 0,
      timeDisabled: true,
      dataAddList: [],
      time: [],
      editEntity: {},
      NumberList: [],
      CodeList: [],
      editEntitya: {},
      sorter: { field: 'dDate', order: 'desc' },
      loading: false,
      columns,
      queryParam: { Condition: 'cCusName' },
      selectedRowKeys: [],
      rules: {
        submitNumber: [{ required: true, message: '请输入发票号码', trigger: 'blur' }],
      },
    }
  },
  methods: {
    repossess() {
      this.queryParam = { Condition: 'cCusName' }
      this.getDataList()
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination = { ...pagination }
      this.filters = { ...filters }

      this.getDataList()
    },
    getDataList() {
      this.selectedRowKeys = []

      this.loading = true
      this.$http.post('/InvoiceManagement/v_outdatanotinvoiced/GetDataListByMoreCondition', {
        PageIndex: this.pagination.current,
        PageRows: this.pagination.pageSize,
        SortField: 'CODE',
        SortType: 'desc',
        // DeptId: this.DeptId,
        Search: [{ ...this.queryParam, BeginDate: this.time[0] ? this.timeFormat(this.time[0]) : "", EndDate: this.time[1] ? this.timeFormat(this.time[1]) : "" }],
        // ...this.filters
      })
        .then(resJson => {
          this.loading = false
          this.data = resJson.Data
          this.data.forEach((item) => {
            item.InvoicingQuantity = parseFloat(item.InvoicingQuantity).toFixed(4)
            item.InvoicingAmount = this.$options.filters.NumberFormats(item.InvoicingAmount)
          })
          if (this.data) {
            const pagination = { ...this.pagination }
            pagination.total = resJson.Total
            this.pagination = pagination
          }
        })
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
    handleAdd() {
      this.$refs.editForm.openForm(null, '新建销售出库单主表信息')
    },
    handleView(id, record) {
      console.log('点击查看', id, record)
      this.$refs.editForm.openForm(record, '出库单详情')
    },
    pushAddList() {
      this.$refs.editEntity.validate((valid) => {
        if (valid) {
          this.editEntity.Invoicenumber = this.editEntity.Invoicenumber + ',' + this.editEntitya.submitNumber || ''
          this.editEntity.Invoicecode = this.editEntity.Invoicecode + ',' + this.editEntitya.submitCode || ''
          this.NumberList = this.editEntity.Invoicenumber.split(',')
          this.CodeList = this.editEntity.Invoicecode.split(',')
          this.editEntitya = {}
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    del(index) {
      this.NumberList.splice(index, 1)
      this.CodeList.splice(index, 1)
      this.editEntity.Invoicenumber = this.NumberList.join(',')
      this.editEntity.Invoicecode = this.CodeList.join(',')
    },
    handleEdit(record) {
      this.editEntity = JSON.parse(JSON.stringify(record))
      this.NumberList = this.editEntity.Invoicenumber.split(',')
      this.CodeList = this.editEntity.Invoicecode.split(',')
      this.visible = true
    },
    handleSubmit(e) {
      this.$http
        .post('/InvoiceManagement/Inv_InvoiceApplyMain/SetInvoiceNumber', {
          Id: this.editEntity.ApplyId,
          Invoicenumber: this.editEntity.Invoicenumber,
          Invoicecode: this.editEntity.Invoicecode,
        })
        .then((res) => {
          if (res.Success) {
            this.$message.success('修改成功!')
            this.visible = false
            this.getDataList()
          } else {
            this.$message.error('修改失败!')
          }
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    handleDelete(ids) {
      var thisObj = this
      // this.$confirm({
      //   title: '确认删除吗?',
      //   onOk() {
      //     return new Promise((resolve, reject) => {
      //       thisObj.$http.post('/OrderManagement/rdrecord32/DeleteData', ids).then(resJson => {
      //         resolve()

      //         if (resJson.Success) {
      //           thisObj.$message.success('操作成功!')

      //           thisObj.getDataList()
      //         } else {
      //           thisObj.$message.error(resJson.Msg)
      //         }
      //       })
      //     })
      //   }
      // })

      this.$confirm('确认作废吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        // thisObj.$http
        //   .post('/OrderManagement/rdrecord32/DeleteData', ids)
        //   .then(resJson => {
        //     // resolve()
        //     if (resJson.Success) {
        //       thisObj.$message.success('操作成功!')
        //       thisObj.getDataList()
        //     } else {
        //       thisObj.$message.error(resJson.Msg)
        //     }
        //   })
      })
    },
    changeTime(e) {
      this.timeDisabled = true
      this.selectTime = e
      this.time = []
      switch (e) {
        case 0:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth(), 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 1:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 2, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 2:
          this.time[0] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() - 5, 1))
          this.time[1] = this.timeFormat(new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0))
          break
        case 3:
          this.timeDisabled = false
          break
      }
    },
    //导出
    downloadTemplate() {
      this.$http
        .post(
          '/InvoiceManagement/v_outdatanotinvoiced/Export',
          {
            Search: [
              {
                ...this.queryParam,
                BeginDate: this.time[0] ? this.timeFormat(this.time[0]) : '',
                EndDate: this.time[1] ? this.timeFormat(this.time[1]) : '',
              },
            ],
          },
          { responseType: 'blob' }
        )
        .then((res) => {
          const url = URL.createObjectURL(res)
          // console.log(url)
          const fileName = '开票状态表'
          const aTag = document.createElement('a')
          aTag.download = fileName
          aTag.href = url
          aTag.click()
          URL.revokeObjectURL(aTag.href)
        })
        .catch((err) => {
          this.$message.error(err)
        })
    },
    timeFormat(val) {
      // 时间格式化函数
      return moment(val).format('YYYY-MM-DD')
    },
    ShowNumber(obj, eclipse) {
      if (eclipse) {
        return invoiceNumberAbbr(obj.Invoicenumber)
      }
      return obj.Invoicenumber
    },
  },
}
</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  padding-bottom: 0px;
}
</style>
